package com.sharecode.stock.strategy.norm.boll;

import java.util.List;

import com.sharecode.stock.strategy.norm.Norm;
import com.sharecode.stock.strategy.vo.Boll;
import com.sharecode.stock.strategy.vo.StrategyVo;
import com.sharecode.stock.vo.stock.StockHistory;

/**
 * BOLL指标
 * 
 * @author Administrator
 *
 */
public class BOLLNorm implements Norm {
	private static final int T = 20;
	private static final int K = 2;

	private static final BOLLNorm bollNorm = new BOLLNorm();

	public static BOLLNorm getInstance() {
		return bollNorm;
	}

	@Override
	public void handle(StrategyVo vo) {
		boll(vo);
	}

	private void boll(StrategyVo vo) {
		List<StockHistory> klines = vo.getStockHistories();
		List<Boll> bolls = vo.getBolls();
		bolls.clear();
		for (int i = T - 1; i < klines.size(); i++) {
			if (i < T - 1) {
				continue;
			}
			double sum = 0;
			for (int j = T - 1; j >= 0; j--) {
				sum += klines.get(i - j).getClose().doubleValue();
			}
			double z = sum / T;
			double sumMD = 0;
			for (int j = T - 1; j >= 0; j--) {
				double thisClose = klines.get(i - j).getClose().doubleValue();
				double cma = thisClose - z; // C-MB
				sumMD += cma * cma;
			}
			double md = Math.pow(sumMD / (T - 1), 1.0 / K); // MD=前n日C-MB的平方和来开根
			double s = z + md * K;
			double x = z - md * K;
			bolls.add(new Boll(getDouble(s), getDouble(z), getDouble(x)));
		}

	}
}